package workorder

import (
	"../common"
	"../web"
	"strconv"
	"strings"
)

type ModifyWorkOrderObj struct {
	common.BaseHandler
}

func (self *ModifyWorkOrderObj) Prepare() {
	items := *common.FetchAllRowsPtr(
		`SELECT ITEM, ISNULL(DESCRIP, '') 
           FROM SFC_ITEMS(NOLOCK) 
          WHERE LOCKED = 0 
          ORDER BY ITEM`,
		self.Usr.Conn, new(common.ItemDesc))

	routings := *common.FetchAllRowsPtr(
		`SELECT DISTINCT NAME 
           FROM SFC_ROUTING(NOLOCK) 
          ORDER BY NAME`,
		self.Usr.Conn, new(common.RouteName))

	wonos := *common.FetchAllRowsPtr(
		`SELECT WONO, WOTYPE, ITEM, '', QTY 
           FROM SFC_WO(NOLOCK) 
          WHERE RELEASED = 0 
            AND LOCKED = 0 
            AND CLOSED = 0 
          ORDER BY WONO`,
		self.Usr.Conn, new(common.WorkOrder))

	self.TmplData["items"] = items
	self.TmplData["routings"] = routings
	self.TmplData["wonos"] = wonos
}

func (self *ModifyWorkOrderObj) ParameterCheck() bool {
	s_wono := self.Ctx.Params["wono"]
	s_type := self.Ctx.Params["wotype"]
	s_item := self.Ctx.Params["item"]
	s_revs := strings.TrimSpace(self.Ctx.Params["rev"])
	s_rout := self.Ctx.Params["rout"]
	s_iqty := strings.TrimSpace(self.Ctx.Params["qty"])
	s_remk := strings.TrimSpace(self.Ctx.Params["remk"])
	if s_wono == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the WorkOrder.")
		return false
	}
	if s_item == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the item.")
		return false
	}
	if s_revs == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the Version.")
		return false
	}
	i_qty, err := strconv.Atoi(s_iqty)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Qty must be a number.")
		return false
	}
	if i_qty < 1 {
		self.TmplData["error"] = common.GetText(self.Lang, "Qty must be more than zero.")
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_wono)
	self.Sqlparas = append(self.Sqlparas, s_type)
	self.Sqlparas = append(self.Sqlparas, s_item)
	self.Sqlparas = append(self.Sqlparas, s_revs)
	self.Sqlparas = append(self.Sqlparas, s_rout)
	self.Sqlparas = append(self.Sqlparas, i_qty)
	self.Sqlparas = append(self.Sqlparas, s_remk)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)
	self.Flashparas = []interface{}{strings.ToUpper(s_wono)}

	return true
}

func (self *ModifyWorkOrderObj) SqlExecute() bool {
	spRtnData := *common.FetchOneRowPtr(
		`sp_ModifyWorkOrder ?, ?, ?, ?, ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	if spRtnData.(common.SPReturn).Flag > 0 {
		self.TmplData["error"] = common.GetTextSP(self.Lang, spRtnData)
		return false
	}
	return true
}

func ModifyWorkOrderHandler(ctx *web.Context) {
	self := new(ModifyWorkOrderObj)
	self.Ctx = ctx
	self.Url = "/modifywo"
	self.Html = "modifywo.html"
	self.Rightlist = []string{"modifywo"}
	self.Flashstr = "Modify WorkOrder: [ %v ] finished."
	self.Do(self)
}
